use std::{collections::HashMap, thread::sleep, time::Duration};

use container_core::workflow::{SimpleWorkflowEngine, WorkflowDocumentJsonReader};
use model_graph_types::{
    container::workflow::{
        WorkflowDocumentReadeOptions, WorkflowDocumentReader, WorkflowEngine,
        WorkflowEngineCompileOptions, WorkflowEngineRunOptions,
    },
    database::{ConnectorProtocol, DataSource as DatabaseDataSource, DatabaseType},
    modeling::{set_system_meta_database, Value},
};

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    tracing_subscriber::fmt()
        .with_max_level(tracing::Level::DEBUG)
        .init();
    tracing::info!("RRAI 启动...");

    set_system_meta_database(DatabaseDataSource {
        id: 0,
        database_type: DatabaseType::SQLite,
        protocol: ConnectorProtocol::SQLite,
        url: String::from("sqlite:/Users/jinisu/rrg01/rrg01.sqlite"),
        ..Default::default()
    })?;

    // let node = WorkflowGraphNode {
    //     id: String::from("...."),
    //     r#type: String::from("...."),
    //     data: WorkflowGraphNodeData::Statement(WorkflowGraphNodeStatement::Http(
    //         WorkflowGraphNodeHttpStatement {
    //             url: String::from("...."),
    //             method: None,
    //         },
    //     )),
    //     parent_id: None,
    // };
    // tracing::info!("{}", serde_json::to_string(&node)?);

    // let document = WorkflowDocumentJsonReader::default()
    //     .read_from_json_file(
    //         &String::from("/Users/jinisu/rrg01/task_001.json"),
    //         WorkflowDocumentReadeOptions::default(),
    //     )
    //     .await?;
    let document = WorkflowDocumentJsonReader::default()
        .read_from_json_file(
            &String::from(
                "/Users/jinisu/rrg01/flows/585f03b5-e439-4786-96d5-6a660aeeb596/workflow.json",
            ),
            WorkflowDocumentReadeOptions::default(),
        )
        .await?;

    let mut args = HashMap::new();

    args.insert(
        String::from("Prompt"),
        Value::String(String::from("二分法如何编写")),
    );

    let res = SimpleWorkflowEngine::default()
        .fetch(
            document,
            args,
            WorkflowEngineCompileOptions::default(),
            WorkflowEngineRunOptions::default(),
        )
        .await;

    match res {
        Ok(response) => {
            tracing::debug!("1{:?}", response);
        }
        Err(err) => {
            tracing::error!("2{:?}", err);
        }
    }
    tokio::select! {
        _ = tokio::signal::ctrl_c() => {
            println!();
        }
    };
    tracing::info!("RRAI 结束...");
    Ok(())
}
